package org.ams.role.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.ams.common.annotation.Log;
import org.ams.common.entity.Pager;
import org.ams.common.exception.SystemException;
import org.ams.common.util.Common;
import org.ams.menu.entity.Menu;
import org.ams.menu.service.MenuService;
import org.ams.role.entity.Role;
import org.ams.role.entity.RoleMenu;
import org.ams.role.service.RoleService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Controller
@Scope("prototype")
@RequestMapping(value = "/role")
public class RoleController {

	@Resource
	private RoleService roleService;
	
	@Resource
	private MenuService menuService;
	
	@RequestMapping(value = "/main", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	public String main(HttpServletRequest request) {
		try{
			request.removeAttribute("error");
			return Common.VIEW_PATH + "/role/list";
		} catch(Exception e) {
			throw new SystemException(e);
		}
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="角色管理-查询")//凡需要处理业务逻辑的.都需要记录操作日志
	public Map<String, Object> list(HttpServletRequest request,@RequestParam ("dtGridPager") String dtGridPager) {
		Map<String, Object> params = null;
		// 映射Pager对象
		Pager pager = JSON.parseObject(dtGridPager, Pager.class);
		// 判断是否包含自定义参数
		params = pager.getParameters();
		// 设置分页，page里面包含了分页信息
		Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize(), true);
		List<Role> accountList = roleService.queryRoleListByPage(params);
		params.clear();
		params.put("isSuccess", Boolean.TRUE);
		params.put("nowPage", pager.getNowPage());
		params.put("pageSize", pager.getPageSize());
		params.put("pageCount", page.getPages());
		params.put("recordCount", page.getTotal());
		params.put("startRecord", page.getStartRow());
		//列表展示数据
		params.put("exhibitDatas", accountList);
		return params;
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="角色管理-删除")//凡需要处理业务逻辑的.都需要记录操作日志
	public Boolean delete(HttpServletRequest request,@RequestParam("ids") String roleIds) {
		Map<String, Object> params = new HashMap<String, Object>();
		List<Integer> idList = Common.createIdList(roleIds, ",");
		params.put("idList", idList);
		Integer returnRows = roleService.deleteRolesByIds(params);
		if(0 < returnRows){
			return true;
		} else {
			return false;
		}
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	@Log(module="系统基础管理",methods="角色管理-新增")//凡需要处理业务逻辑的.都需要记录操作日志
	public String add(HttpServletRequest request, Model model) {
		try{
			request.removeAttribute("error");
			List<Menu> menuList = menuTree();
			model.addAttribute("menuList", menuList);
			model.addAttribute("operation", "add");
			return Common.VIEW_PATH + "/role/info";
		} catch(Exception e) {
			throw new SystemException(e);
		}
	}
	
	@RequestMapping(value = "/{roleId}/edit", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	@Log(module="系统基础管理",methods="角色管理-编辑")//凡需要处理业务逻辑的.都需要记录操作日志
	public String edit(HttpServletRequest request,@PathVariable("roleId") Integer roleId, Model model) {
		try{
			Map<String, Object> params = new HashMap<String, Object>();
			request.removeAttribute("error");
			List<Menu> menuList = menuTree();
			params.put("roleId", roleId);
			Role role = roleService.queryRoleByMap(params);
			List<RoleMenu> roleMenuList = roleService.queryRoleMenuListByRoleId(roleId);
			for (RoleMenu roleMenu : roleMenuList) {
				for (Menu menu : menuList) {
					if(menu.getMenuId().toString().equals(roleMenu.getMenuId().toString())){
						menu.setChecked(true);
					}
					for (Menu son : menu.getChildren()) {
						if(son.getMenuId().toString().equals(roleMenu.getMenuId().toString())){
							son.setChecked(true);
						}
						for (Menu children : son.getChildren()) {
							if(children.getMenuId().toString().equals(roleMenu.getMenuId().toString())){
								children.setChecked(true);
							}
						}
					}
				}
			}
			model.addAttribute("menuList", menuList);
			model.addAttribute("operation", "edit");
			model.addAttribute("role", role);
			return Common.VIEW_PATH + "/role/info";
		} catch(Exception e) {
			throw new SystemException(e);
		}
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="角色管理-保存")//凡需要处理业务逻辑的.都需要记录操作日志
	public Boolean save(HttpServletRequest request, Role role) {
		if(null != role.getRoleId() && 0 < role.getRoleId()){
			role.setUpdateTime(new Date());
			Integer returnRows = roleService.updateRole(role);
			if(0 < returnRows) {
				return true;
			} else {
				return false;
			}
		} else {
			role.setCreateTime(new Date());
			role.setUpdateTime(new Date());
	        Integer returnRows = roleService.saveRole(role);
			if(0 < returnRows){
				return true;
			} else {
				return false;
			}
		}
	}
	
	private List<Menu> menuTree(){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("parentId", 0);
		params.put("menuLevel", 1);
		List<Menu> menuList = menuService.queryMenuListByMap(params);
		for (Menu menu : menuList) {
			params.clear();
			params.put("parentId", menu.getMenuId());
			params.put("menuLevel", menu.getMenuLevel() + 1);
			List<Menu> sonList = menuService.queryMenuListByMap(params);
			menu.setChildren(sonList);
			for (Menu son : sonList) {
				params.clear();
				params.put("parentId", son.getMenuId());
				params.put("menuLevel", son.getMenuLevel() + 1);
				List<Menu> childrenList = menuService.queryMenuListByMap(params);
				son.setChildren(childrenList);
			}
		}
		System.out.println(JSONArray.toJSON(menuList));
		return menuList;
	}
}
